package list;

public class Demo11 {
    public static void main(String[] args) {
        /*
         * 7进制 123 转换为 int
         * 结果为 66
         */
        int n = Integer.parseInt("123", 7);
        System.out.println(n); //按照10进制输出
        n = parseInt("123", 7);
        System.out.println(n);
    }
    public static int parseInt(String num, int radix){
        //negative 负数
        boolean negative = num.charAt(0) == '-';//检查是否有符号
        num = negative ? num.substring(1) : num;//有符号时候先去掉负号
        int sum = 0;
        int weight = 1;
        for(int i=num.length()-1; i>=0; i--){
            char c = num.charAt(i);
            int n = c - '0';
            if (n<0 || n>=radix){
               throw new NumberFormatException("数字错误:"+c);
            }
            sum += n * weight;
            weight *= radix;
        }
        return negative ? -sum : sum;//负数时候取相反数
    }
}
